package com.tinshow.web.controller.topic;

import com.alibaba.fastjson.JSONObject;
import com.tinshow.config.cookie.CookieUtil;
import com.tinshow.model.article.Article;
import com.tinshow.model.article.vo.ArticleVo;
import com.tinshow.model.json.JsonResult;
import com.tinshow.model.user.User;
import com.tinshow.service.index.ArticleService;
import com.tinshow.service.user.UserService;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by libo4 on 2017-05-12.
 */
@Controller
public class TopicsController {

    @Autowired
    ArticleService articleService;
    @Autowired
    UserService userService;

    @RequestMapping(value = "/topics")
    public ModelAndView topics(Model model){
        ArticleVo vo = new ArticleVo();
        List<ArticleVo> aList = articleService.getArticleAndUser(vo);
        Document doc = null;
        for (ArticleVo articleVo : aList) {
            doc = Jsoup.parse(articleVo.getContent());
            String content = doc.text();
            articleVo.setContent(content.substring(0,100));
        }
        model.addAttribute("article_list", aList);
        return new ModelAndView("topic/topics").addObject(model);
    }

    @RequestMapping(value = "/article/edit")
    public ModelAndView artielEdit(Model model, HttpServletRequest request){
        JSONObject jsonObject = CookieUtil.getSession(request);
        if(jsonObject == null){
            return new ModelAndView("redirect:/login_view");
        }
        return new ModelAndView("topic/article_edit").addObject(model);
    }

    @RequestMapping("/article/submit")
    @ResponseBody
    public Object submitArticle(Model model, @RequestParam("title") String title,
                                @RequestParam("abstract") String abstract_txt,
                                @RequestParam("context") String context,
                                @RequestParam("tags") String tags,
                                @RequestParam("classification_id") Integer classification_id,
                                @RequestParam("type") String type,
                                @RequestParam("reprinted_url") String reprinted_url,
                                HttpServletRequest request){
        Article article  = new Article();
        article.setTitle(title);
        if(StringUtils.isNotEmpty(abstract_txt)){
            article.setAbstractTxt(abstract_txt);
        }
        article.setContent(context);
        article.setClassificationId(classification_id);
        article.setType(type);
        Document doc = Jsoup.parse(context);
        Elements elements = doc.getElementsByTag("img");
        if (!elements.isEmpty()){
            System.out.println(elements);
            String img = elements.get(0).attr("src");
            if(StringUtils.isNotEmpty(img)){
                article.setMainImageUrl(img);
            }
        }
        JSONObject jsonObject = CookieUtil.getSession(request);
        article.setAuthId(Integer.parseInt(jsonObject.getString("userId")));
        if ("reprinted".equals(type)){
            article.setReprintedDes(reprinted_url);
        }
        JsonResult jsonResult = new JsonResult();
        try {
            int article_id = articleService.insertArticle(article);
            if(article_id > 0) {
                jsonResult.setSuccess(1);
                jsonResult.setMsg("发表成功");
                Map<String,Integer> dataMap = new HashMap<>();
                dataMap.put("article_id",article.getArticelId());
                jsonResult.setData(dataMap);
            }
        } catch (Exception e) {
            jsonResult.setSuccess(0);
            jsonResult.setMsg("发表文章异常");
        }
        return jsonResult;
    }

    @RequestMapping("/article/detail/{articleId}")
    public ModelAndView getArticleDetail(Model model, @PathVariable Integer articleId){
        ArticleVo article = articleService.getArticleById(articleId);
        if(StringUtils.isEmpty(article.getAbstractTxt())){
            Document doc = Jsoup.parse(article.getContent());
            String abstractTxt = doc.text().substring(0,100);
            article.setAbstractTxt(abstractTxt);
        }
        User user = userService.selectUserById(article.getAuthId());
        article.setUser(user);
        model.addAttribute("article", article);
        return new ModelAndView("topic/article_detail").addObject(model);
    }

    @RequestMapping("/article/submit_baidu_sitemap")
    @ResponseBody
    public Object submitBaiduSitemap(){

        return null;
    }
}
